#include "SocketIO.hpp"
#include <asm-generic/socket.h>
#include <cerrno>
#include <pthread.h>
#include <sys/socket.h>

namespace wd{

SocketIO::SocketIO(int clientfd)
:_fd(clientfd)
{
}

SocketIO::~SocketIO(){
    close(_fd);
}


int SocketIO::readn(char* buff, int len){
    int left = len;
    char * curbuf = buff;
    while(left > 0){
        int ret = recv(_fd,curbuf,left,0);
        if(ret == -1 && errno == EINTR){
            continue;
        }else if(ret == -1){
            perror("recv");
            return ret;
        }else if(ret == 0){
            return len-left;
        }else{
            left -= ret;
            curbuf += ret;
        }
    }
    return len;
}

int SocketIO::sendn(const char* buff, int len){
    int left = len;
    const char * curbuf = buff;
    while(left > 0){
        int ret = send(_fd,curbuf,left,0);
        if(ret < 0){
            perror("send");
            return ret;
        }else{
            left -= ret;
            curbuf += ret;
        }
    }
    return len;
}
int SocketIO::recvPeek(char * buff, int maxlen){
    int ret = 0;
    do{
        ret = recv(_fd,buff,maxlen,MSG_PEEK);
    }while(ret == -1 && errno == EINTR);
    if(ret < 0){
        perror("recv");
    }
    return ret;
}

int SocketIO::readline(char * buff, int maxlen){

    int left = maxlen-1;
    char * curbuf = buff;
    int total = 0;
    while(left > 0){
       int ret = recvPeek(curbuf,left);
        //找'\n'
       for(int i = 0;i < ret; ++i){
           if(curbuf[i] == '\n'){
                int sz = i + 1;//包含'\n'
                ret = readn(curbuf,sz);
                if(ret < 0){
                    return ret;
                }
                curbuf[i] = '\0'; 
                return total + ret; 
           }
       }
       //没找到
       ret = readn(curbuf,ret); 
       if(ret < 0){
            return ret;
       }
       left -= ret;
       curbuf += ret;
       total += ret;
    }
    buff[maxlen-1] = '\0';
    return maxlen -1;
}

}

